 <!DOCTYPE html>
 
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %> 
<%@ page import="java.io.*" %> 
<%@ page import="java.util.Date" %> 
<%@ page import="java.text.DateFormat" %> 
<%@ page import="java.text.SimpleDateFormat" %> 

<html>
	<head>
		<script type="text/javascript">
			function fileUploadStart(s_flag)
			{
				if (s_flag >= 1){
					document.getElementsByName("dat_action_flag")[0].value = 1;
				}else
				{
					document.getElementsByName("dat_action_flag")[0].value = 0;
				}
			}
		</script>
		<link rel="stylesheet" type="text/css" href="common.css">
	<title>Submit Assignment</title>
	</head>
	<body>
		<form action="single_upload_page.jsp" method="post" name="entry" onSubmit="return validate(this)">
			<table class="TblBody" style="width:720px">
				<tr>
					<td>
						<div class="contentb">
						<table width="100%">
							<tr>
								<td style="background-color:#ccff99; font-size:20px; font-weight:bold; width:70%; height:30px">
									Submit Assignment
								</td>
							</tr>
							<tr>
								<td>
									<input type="hidden" value="0" name="dat_action_flag" />
									<u>File ready for submition</u>
									<br />
			<%
													
									Boolean chk_flag = true;
									//to get the content type information from JSP Request Header
									String contentType = request.getContentType();
									//here we are checking the content type is not equal to Null and
									//as well as the passed data from mulitpart/form-data is greater than or
									//equal to 0
									if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) 
									{
										
										DataInputStream in = new DataInputStream(request.getInputStream());
										//we are taking the length of Content type data
										int formDataLength = request.getContentLength();
										byte dataBytes[] = new byte[formDataLength];
										int byteRead = 0;
										int totalBytesRead = 0;
										//this loop converting the uploaded file into byte code
										while (totalBytesRead < formDataLength) 
										{
											byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
											totalBytesRead += byteRead;
										}
										String file = new String(dataBytes);
										//for saving the file name
										String saveFile = file.substring(file.indexOf("filename=\"") + 10);
										saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
										saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
										int lastIndex = contentType.lastIndexOf("=");
										String boundary = contentType.substring(lastIndex + 1,contentType.length());
										int pos;
										//extracting the index of file 
										pos = file.indexOf("filename=\"");
										pos = file.indexOf("\n", pos) + 1;
										pos = file.indexOf("\n", pos) + 1;
										pos = file.indexOf("\n", pos) + 1;
										int boundaryLocation = file.indexOf(boundary, pos) - 4;
										int startPos = ((file.substring(0, pos)).getBytes()).length;
										int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
										int maxFileSize = (1024 * 1024 * 3);
										// creating a new file with the same name and writing the content in new file
										//FileOutputStream fileOut = new FileOutputStream("..//assignment_submit//" + saveFile);
										//fileOut.write(dataBytes, startPos, (endPos - startPos));
										//fileOut.flush();
										//fileOut.close();
										
										if ((endPos - startPos) > maxFileSize){
											chk_flag = false;
											session.setAttribute( "upload_flag", "0");
										}
										else{
											chk_flag = true;
											session.setAttribute( "upload_flag", "1");
										}
										
										session.setAttribute( "StartPos", startPos);
										session.setAttribute( "EndPos",  endPos);
										session.setAttribute( "FormDataLength",  formDataLength);
										session.setAttribute( "SaveFile", saveFile);
										
				%>
					
										<% if (chk_flag == true) { %>
										<table class="SubTable" width="350px">
											<tr>
												<th>File Name</th>
												<th>Size</th>
												<th>Status</th>
											</tr>
											<tr>
												<td><% out.println(saveFile); %></td>
												<td><% out.println(endPos - startPos); %></td>
												<td>OK</td>
											</tr>
										</table>
										<%}else{%>
										<table class="SubTable">
											<tr>
												<th>File Name</th>
												<th>Size</th>
												<th>Status</th>
											</tr>
											<tr>
												<td><% out.println(saveFile); %></td>
												<td style="color:red"><% out.println(endPos - startPos); %></td>
												<td>Reject</td>
											</tr>
										</table>
										<%}%>
			<%
									}
									
									String action_flag = request.getParameter("dat_action_flag");
									
									if (action_flag != null && action_flag != "")
									{
										int _upload_flag = Integer.parseInt((session.getAttribute("upload_flag")).toString());
										int int_act_flag = Integer.parseInt(action_flag);
										
										if(int_act_flag >= 1 && _upload_flag == 1)
										{
										
											String user_id = (String)session.getAttribute("UserID");
											int start_pos = Integer.parseInt((session.getAttribute("StartPos")).toString());
											int end_pos = Integer.parseInt((session.getAttribute("EndPos")).toString());
											int data_length = Integer.parseInt((session.getAttribute("FormDataLength")).toString());
											String save_file = (String)session.getAttribute("SaveFile");
											
											byte tmpfile[] = new byte[data_length];
											
											FileOutputStream fileOut = new FileOutputStream("C://" + save_file);
											fileOut.write(tmpfile, start_pos, (end_pos - start_pos));
											fileOut.flush();
											fileOut.close();
											
											session.removeAttribute("StartPos");
											session.removeAttribute("EndPos");
											session.removeAttribute("FormDataLength");
											session.removeAttribute("SaveFile");
											
											//database update part//
											try {
												
												String connectionURL = "jdbc:mysql://localhost:3306/unilearn"; 
				
												int c_row_count = 0;
												Connection con = null;
												Statement stmt = null;
												ResultSet rst=null;

												Class.forName("com.mysql.jdbc.Driver").newInstance(); 

												con = DriverManager.getConnection(connectionURL, "root", "");
												stmt = con.createStatement();
												
												if(!con.isClosed())
												{
													int result_count = 0;
													String _user_group_id = "";
													String _commit_user = "";
													int _assignment_id = Integer.parseInt(session.getAttribute("AssignmentID").toString());
													int _assignment_type = Integer.parseInt(session.getAttribute("AssignmentType").toString());
													
													DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
													Date _now = new Date();
													
													//out.println("BVBBBBB" + _assignment_type);
													//out.println("AAAAAAA" + _assignment_id);
													
													
													if (_assignment_type > 1)
													{
														rst = stmt.executeQuery("select * from group_tbl " + 
																				"where assignment_id = '"+ _assignment_id +"' and user_id = '"+ user_id +"'");
														while(rst.next())
														{
															if(rst.getString("user_group_id") != "")
																_user_group_id = rst.getString("user_group_id");
														}
														
														if (_user_group_id == "" || _user_group_id == null)
														{
															out.println( "<script>alert('this is group assihnment. But not created group')</script>" );
														}
													}
													
													
													result_count = stmt.executeUpdate("INSERT INTO assignment_submission (assignment_id, user_group_id , commit_user, commit_date, commit_file_path, create_date, modify_date )" 
															+ "VALUES ('"+_assignment_id+"', '"+_user_group_id+"', '"+user_id+"', '"+dateFormat.format(_now)+"', '"+save_file+"', '"+dateFormat.format(_now)+"', '"+dateFormat.format(_now)+"')");
															
													
													if(result_count > 0) {
														response.sendRedirect("assignment_print_result.jsp");
													}else
													{
														out.println( "<script>alert('assignment submit fail')</script>" );
													}
												}
												
											}catch(Exception ex){

												out.println(ex);
											}
										}
									}

			%>
								<br />
								<input type="submit" value="Submit" name="btnSubmit" Onclick="fileUploadStart(1)" />
								&nbsp;&nbsp;
								<input type="button" value="Cancel" name="btnCancel" />
								</td>
							</tr>
						</table>
						</div>
					</td>
				</tr>
			</table>
		</form>
	</body>
</html>
